package com.itheima.Filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//登录过滤器

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
    public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
   public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        //类型转换
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;


        //获取当前(本次请求的)url；
        String uri = request.getRequestURI();

        //定义不需过滤的请求
        String[] url = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
        };
        //日志打印
        log.info("拦截到请求：{}",uri);

        //判断本次请求是否需要处理
        boolean check=check(url,uri);

        //如果为trun不需要拦截直接放行
        if (check){
            log.info("本次请求{}不需要处理",uri);
            filterChain.doFilter(request,response);
            return;
        }

        //若已登录就 不需要拦截直接放行
        if (request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));

            //修改的 ThreadLocal
            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);

            filterChain.doFilter(request,response);
            return;
        }

        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        //没登录就直接拦截
        log.info("没用登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    //判断是否进行拦截
    public boolean check(String[] url,String uri){
        for (String s : url) {

          boolean match = PATH_MATCHER.match(s, uri);
           if (match){
               return true;
           }
           }return false;
    }
}
